package cn.cimoc.filter;

import cn.cimoc.constant.ConstantPool;
import cn.cimoc.handler.HttpStatusLoginFailureHandler;
import cn.cimoc.handler.JsonLoginSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    public JwtAuthenticationFilter(AuthenticationManager manager, AuthenticationFailureHandler failureHandler, AuthenticationSuccessHandler successHandler) {
        super(new AntPathRequestMatcher("/users/login", "POST"));
        setAuthenticationManager(manager);
        setAuthenticationFailureHandler(failureHandler);
        setAuthenticationSuccessHandler(successHandler);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String username = request.getParameter(ConstantPool.USERNAME);
        String password = request.getParameter(ConstantPool.PASSWORD);
        username = username == null ? "" : username;
        password = password == null ? "" : password;
        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
